package com.yunchao.feature.base.data

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import com.yunchao.feature.base.R


class CustomAudioManager(context: Context) {

    private val soundPool: SoundPool by lazy {
        SoundPool.Builder()
            .setMaxStreams(10)
            .setAudioAttributes(
                AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build()
            )
            .build()
    }

    private val soundMap: Map<Int, Int> by lazy {
        mapOf(
            1 to soundPool.load(context, R.raw.barcodebeep, 1),
            2 to soundPool.load(context, R.raw.serror, 1)
        )
    }

    private val am: AudioManager by lazy {
        context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    }

    /**
     * 播放提示音
     *
     * @param id 成功音1，失败音2
     */
    fun playSound(id: Int) {
        val soundId = soundMap[id] ?: throw IllegalArgumentException("Sound not found for id: $id")
        val audioMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toFloat() // 最大音量
        val audioCurrentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() // 当前音量
        val volumeRatio = audioCurrentVolume / audioMaxVolume // 音量比例

        soundPool.play(
            soundId,          // 声音资源ID
            volumeRatio,      // 左声道音量
            volumeRatio,      // 右声道音量
            1,                // 优先级，0为最低
            0,                // 循环次数，0为不循环，-1为永远循环
            1f                // 播放速度，范围0.5-2.0，1为正常速度
        )
    }
}



